package com.myself.ldap;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import java.util.*;

public class LdapJNDI {

//    private static String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
////    private static String ldapURL = "ldap://10.10.25.229:389";
////    private static String ldapUserName = "cn=idsinst";
////    private static String ldapPassWd = "W0RD2012";
////    private static String base = "dc=P1";

    private static String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
    private static String ldapURL = "ldap://10.8.18.188:389";
    private static String ldapUserName = "cn=idsinst";
    private static String ldapPassWd = "P@SSW0RD2012";
    private static String base = "dc=PICC";

    /**
     * 创建ldap连接
     *
     * @throws SecurityException
     */
    public static InitialLdapContext getInitialLdapContext()
            throws SecurityException {
        InitialLdapContext currentCtx = null;
        try {
            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
            env.put(Context.PROVIDER_URL, ldapURL);
            env.put(Context.SECURITY_PRINCIPAL, ldapUserName);
            env.put(Context.SECURITY_CREDENTIALS, ldapPassWd);
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            currentCtx = new InitialLdapContext(env, null);
        } catch (NamingException ne) {
            throw new SecurityException(ne);
        }
        return currentCtx;
    }

    public static void main(String[] args) {

//        InitialLdapContext context = getInitialLdapContext();
//        String id = "20120625222107064049tme";
//        String DN = getLdapUserDN(context,id);
//
//        String newPassWd = "qwe123";
//        String newPosition = "";
//        String newMail = "";
//
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("userPassword", newPassWd);
//        params.put("uuPosition", newPosition);
//        params.put("mail", newMail);
//
//        modifyEntry(context,DN,params);


        String s = "znPaPLXM4jZ4G8J5KLtuF9oGQ7QCpXQ7";
        String s1 = "9tFOmPSzm/+JPmGCFDdVZhdB6ojVNewv";
        String s2 = "9tFOmPSzm/+JPmGCFDdVZhdB6ojVNewv";
        try {
//            System.out.println(new CryptoTools().decode(s));
//            System.out.println(new CryptoTools().decode(s1));
//            System.out.println(new CryptoTools().decode(s2));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * modifyEntry：修改条目,<br>
     * @param ctx InitialLdapContext LDAP连接
     * @param entryDN String 新条目的完整DN
     * @param entryAttrs Map 新条目的属性-值
     */
    public static void modifyEntry(InitialLdapContext ctx, String entryDN, Map entryAttrs){

        Attributes attrs = new BasicAttributes(true);
        if(entryAttrs!=null && !entryAttrs.isEmpty()){

            Object o;
            String val = "";
            Attribute attr = null;
            Iterator iterator = entryAttrs.keySet().iterator();

            while(iterator.hasNext()){

                o=iterator.next();
                attr = new BasicAttribute(o.toString());
                //get values
                val = entryAttrs.get(o.toString())==null?"":entryAttrs.get(o.toString()).toString();
                String[] vals = val.split(", ");
                if(vals.length>0){
                    for(int i=0; i<vals.length; i++){
                        attr.add(vals[i]);
                    }
                }
                attrs.put(attr);
            }
        }

        try {
            ctx.modifyAttributes(entryDN, DirContext.REPLACE_ATTRIBUTE, attrs);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public static String getLdapUserDN(InitialLdapContext context, String uid){

        String resultDN = "";

        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "(&(&(objectclass=inetOrgPerson)(objectclass=uuPerson))(uuGlobalId=" + uid + "))";

        try {
            NamingEnumeration<SearchResult> namingenumeration = context.search(base, filter, controls);
            if (namingenumeration != null) {
                while (namingenumeration.hasMore()) {
                    SearchResult searchresult = (SearchResult) namingenumeration.next();
                    //遍历每一个条目

                    Hashtable ent = new Hashtable();
                    Attributes attributeSet = searchresult.getAttributes();
                    resultDN = base.length() > 0 ? searchresult.getName() + "," + base : searchresult.getName();
                    System.out.println(attributeSet.get("cn"));
                    System.out.println(attributeSet.get("Title"));
                }
            }
        } catch (NamingException e) {
            e.printStackTrace();
        }

        return resultDN;
    }

}
